//用户相关方法

const {
    execSQL
} = require('../db/mysql')

const {
    generateToken,
    verifyToken,
    generatePassword,
    decodePassword
} = require('../utils')


//获取购物车数据
const getCart = ({
    uid
}) => {
    let sql = `select data from cart where userId = '${uid}'`
    return execSQL(sql).then(res => {
        return res[0]
    }).catch(e => {
        return false;
    })
}



//更新未登录前购物车数据
const updateCart = async ({
    uid,
    data
}) => {
    
    let originalData,sql,isEmpty;
    await getCart({uid}).then(res=>{
        if(res){
            originalData = JSON.parse(res.data);

        }else{
            originalData = {};
            isEmpty =  true;

        }

    }).catch((e)=>{
        
        throw e;
    })

    let newData = JSON.parse(data);
    
    for(let shopId in newData){
        if(Object.keys(originalData).includes(shopId)){
            let newGoods = Object.keys(newData[shopId]);

            for(let good of newGoods){
                originalData[shopId][good] = newData[shopId][good];
            }
        }else{
            originalData[shopId] = newData[shopId];
        }
    }

    if(isEmpty){
        sql = `insert into cart (userId,data) values('${uid}','${JSON.stringify(originalData)}')`;
    }else{
        sql = `update cart set data = '${JSON.stringify(originalData)}' where userId = '${uid}'`
    }
    
    

    console.log('更新未登录前购物车数据',newData,"!",originalData,"!!")
    return execSQL(sql).then(res => {
        return res.affectedRows > 0;
    }).catch(e => {
        throw e;
        return false;
    })
    
}

//已登录同步购物车
const syncCart = async ({uid,data})=>{
    let sql,isEmpty;
    
    await getCart({uid}).then(res=>{
        isEmpty = res ? false:true;

    })
    
    
    if(isEmpty){
        sql = `insert into cart (userId,data) values('${uid}','${data}')`;
    }else{
        sql = `update cart set data = '${data}' where userId = '${uid}'`
    }

    return execSQL(sql).then(res => {
        return res.affectedRows > 0;
    }).catch(e => {

        return false;
    })
}



//获取用户收藏信息
const getCollection = ({uid})=>{
    let sql = `select collection from  users  where id = '${uid}'`

    return execSQL(sql).then(res => {

        return res[0];
    }).catch(e => {
        throw e;

    })
};


//更新用户收藏信息
const updateCollection = async ({uid,data})=>{
    let sql = `update users set collection = '${data}' where id = '${uid}'`

    
    return execSQL(sql).then(res => {

        return res.affectedRows > 0;
    }).catch(e => {
        throw e;

    })
};


//获取用户浏览记录
const getViewed = ({uid})=>{
    let sql = `select viewed from  users  where id = '${uid}'`

    return execSQL(sql).then(res => {

        return res[0];
    }).catch(e => {
        throw e;

    })
};

//更新用户浏览记录
const updateViewed = async ({uid,data})=>{
    let sql = `update users set viewed = '${data}' where id = '${uid}'`
    
    return execSQL(sql).then(res => {

        return res.affectedRows > 0;
    }).catch(e => {
        throw e;
        return false;
    })
};


//获取用户收货地址
const getUserAddress =({uid})=>{
    let sql = `select * from  address  where userId = '${uid}'`

    return execSQL(sql).then(res => {
  
        return res.length ? res:false;
    }).catch(e => {
        throw e;
        return false;
    })
};


//添加用户收货地址
const addUserAddress = async ({uid,data})=>{
    let sql,isEmpty;

    sql = `insert into address (userId,phone,receiver,province,city,address) values('${uid}','${data.phone}','${data.receiver}','${data.province}','${data.city}','${data.address}')`;

    return execSQL(sql).then(res => {

        return res.affectedRows > 0;
    }).catch(e => {
        throw e;
        return false;
    })
};


//获取用户单条收货地址信息
const getUserOneAddress =({uid,i})=>{
    let sql = `select * from  address  where userId = '${uid}' and i ='${i}'`

    return execSQL(sql).then(res => {

        return res.length ? res:false;
    }).catch(e => {
        throw e;
        return false;
    })
};


//更新用户收货地址信息
const updateUserAddress = async ({uid,data})=>{
    let sql,isEmpty;

    sql = `update address set phone = '${data.phone}' ,receiver = '${data.receiver}',province = '${data.province}' ,city = '${data.city}' , address =  '${data.address}' where userId='${uid}' and i = '${data.i}'`;

    return execSQL(sql).then(res => {

        return res.affectedRows > 0;
    }).catch(e => {
        throw e;
        return false;
    })
};


//删除收货地址
const deleteUserAddress = async ({uid,i})=>{
    let sql,isEmpty;

    sql = `delete from address where userId='${uid}' and i = '${i}'`;

    return execSQL(sql).then(res => {

        return res.affectedRows > 0;
    }).catch(e => {
        throw e;
        return false;
    })
};


//登录密码是否正确
const isValidPassword = ({uid,pwd})=>{
     let sql = `select password from users where id='${uid}'`;

    return execSQL(sql).then(res => {

        return pwd == decodePassword(res[0].password);
    }).catch(e => {
        throw e;
        return false;
    })
}

//更新登录密码
const updatePassword = ({uid,pwd})=>{
    let sql = `update users set password = '${generatePassword(pwd)}' where id ='${uid}'`;

    return execSQL(sql).then(res => {

        return res.affectedRows > 0;
    }).catch(e => {
        throw e;
        return false;
    })
}

//是否已设置支付密码
const hasPayPassword = ({uid})=>{
     let sql = `select pay_password  from users where id='${uid}'`;

    return execSQL(sql).then(res => {
        return res[0].pay_password;
    }).catch(e => {
        throw e;
        return false;
    })
}

//支付密码是否正确
const isValidPayPassword = ({uid,pwd})=>{
    let sql = `select pay_password  from users where id='${uid}'`;
    
 return execSQL(sql).then(res => {
     
        return  pwd == decodePassword(res[0].pay_password);
    }).catch(e => {
        throw e;
        return false;
    })
}




//更新支付密码
const setPayPassword = ({uid,pwd})=>{

    
    let sql = `update users set pay_password = '${generatePassword(pwd)}' where id ='${uid}'`;

    return execSQL(sql).then(res => {

        return res.affectedRows > 0;
    }).catch(e => {
        throw e;
        return false;
    })
}

//更改用户昵称
const setNickname = ({uid,nickname})=>{


    let sql = `update users set nickname = '${nickname}' where id ='${uid}'`;

    return execSQL(sql).then(res => {

        return res.affectedRows > 0;
    }).catch(e => {
        throw e;
        return false;
    })
}





module.exports = {
    getCart,
    updateCart,
    syncCart,
    getCollection,
    updateCollection,
    updateViewed,
    getViewed,
    updateUserAddress,
    getUserAddress,
    getUserOneAddress,
    addUserAddress,
    isValidPassword,
    updatePassword,
    hasPayPassword,
    isValidPayPassword,
    setPayPassword,
    setNickname,
    deleteUserAddress
    
    
    
}